<?php

namespace App\Services;

use App\Exceptions\AuthException;
use App\Models\AggregateFixReport;
use App\Models\AggregateReport;
use App\Models\District;
use App\Models\SubTask;
use App\Models\Task;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;

class HomeService
{
    private $currentMonth;
    private $nextMonth;

    public function __construct()
    {
        $this->currentMonth = date('Y-m-01 00:00:00');
        $this->nextMonth = date('Y-m-01 00:00:00', strtotime('+1 month'));
    }


    public function stat($request)
    {
        //本月新增工单
        $result['sub_task_create_count'] = $this->getSubTaskCreateCount();
        //本月待办任务
        $result['task_to_do_count'] = $this->getTaskTodoCount();
        //本月完结任务
        $result['task_complete_count'] = $this->getTaskCompleteCount();
        //本月生成报表
        $result['aggregate_create_count'] = $this->getAggregateCreateCount();
        //本月上报报表
        $result['aggregate_fix_report_count'] = $this->getAggregateFixReportCount();
        //待处理工单
        $result['sub_task_list'] = $this->getSubTaskList($request);
        //待处理任务
        $result['task_list'] = $this->getTaskList();

        return $result;
    }

    public function getSubTaskCreateCount()
    {
        $count = SubTask::where('created_at', '>=', $this->currentMonth)->where('created_at', '<', $this->nextMonth)->count();
        return $count;
    }

    public function getTaskTodoCount()
    {
        $count = Task::query()->where('updated_at', '>=', $this->currentMonth)
            ->where('updated_at', '<', $this->nextMonth)
            ->where('status', '!=', Task::STATUS_COMPLETED)
            ->count();
        return $count;
    }

    public function getTaskCompleteCount()
    {
        $count = Task::where('updated_at', '>=', $this->currentMonth)
            ->where('updated_at', '<', $this->nextMonth)
            ->where(['status' => Task::STATUS_COMPLETED])
            ->count();
        return $count;
    }

    public function getAggregateCreateCount()
    {
        $count = AggregateReport::query()->where('created_at', '>=', $this->currentMonth)
            ->where('created_at', '<', $this->nextMonth)
            ->count();
        return $count;
    }

    public function getAggregateFixReportCount()
    {
        $count = AggregateFixReport::query()->where('created_at', '>=', $this->currentMonth)
            ->where('created_at', '<', $this->nextMonth)
            ->count();
        return $count;
    }

    public function getSubTaskList($request)
    {
        if (!Auth::user()->hasAnyPermission(['sub-task-report', 'sub-task-review1', 'sub-task-review2'])) {
            return [];
        }

        $query = SubTask::has('task')->select(['id', 'updated_at', 'task_id', 'status'])->with('task');

        if (Auth::user()->district_id != District::CITY_ID) {
            $query->where('district_id', Auth::user()->district_id);
        }

        $query->where('status', '!=', SubTask::STATUS_COMPLETED);
        $result['total'] = $query->count();

        $perPage = $request->per_page ?? 10;
        $res = $query->orderBy('updated_at', 'desc')->paginate($perPage)->toArray();
        $result['data'] = $res['data'] ? $res['data'] : [];

        return $result;
    }

    public function getTaskList()
    {
        if (!Auth::user()->hasPermissionTo('task-publish')) {
            return [];
        }

        $tasks = Task::query()->select(['id', 'name', 'status'])->where('status', '!=', Task::STATUS_COMPLETED)->get()->toArray();
        if (empty($tasks)) {
            return [];
        }

        foreach ($tasks as &$task) {
            $task['todo_count'] = SubTask::query()->where(['task_id' => $task['id']])->whereNotIn('status', [SubTask::STATUS_COMPLETED, SubTask::STATUS_REJECTION1, SubTask::STATUS_REJECTION2])->count();
            $task['complete_count'] = SubTask::query()->where(['task_id' => $task['id']])->where('status', SubTask::STATUS_COMPLETED)->count();
            $task['reject_count'] = SubTask::query()->where(['task_id' => $task['id']])->whereIn('status', [SubTask::STATUS_REJECTION1, SubTask::STATUS_REJECTION2])->count();
            $totalCount = $task['todo_count'] + $task['complete_count'] + $task['reject_count'];
            $task['todo_percent'] = $totalCount ? round($task['todo_count'] / $totalCount * 100, 1) : 0;
            $task['complete_percent'] = $totalCount ? round($task['complete_count'] / $totalCount * 100, 1) : 0;
            $task['reject_percent'] = $totalCount ? round($task['reject_count'] / $totalCount * 100, 1) : 0;
        }

        return $tasks;
    }
}
